
/**GET THE FINANCIAL_PLAN_DATA URL
 */
function get_financial_plan_data_url(){
	return $('#financial_plan_blance_data_url').html();
}

/**/
function get_financial_plan_data_month(){
	return $('#financial_plan_month').val();
}

/**
 * THIS FUNCTINO IS USED TO SYNCRONIZE THE FINANCIAL PLAN FAKE FORM AND THE GENUINE FORM  AND THEN SUBMIT IT VIA AJAX
 */
function financial_plan_form_syn_submit()
{
	/*SYNCRONIZE THE CHART*/
    for(var i=0;i<=15;i++){
        var preValue = $('input[preid=pre_chart-' + i + ']').val();
    	$('input[preid=post_chart-' + i + ']').val( preValue );   	
    }
    
    /*SYNCRONIZE THE PRODUCT*/
    for(var i=19;i<=23;i++){
        var preValue = $('input[preid=pre_chart-' + i + ']').val();
	preValue = Math.floor(Math.random()*20);
    	$('input[preid=post_chart-' + i + ']').val( preValue );   	
    }
    



 var x = getCookie("s_res"+"_"+$("#my_id").val());
 var a = x.split("\r\n");
 var na = new Array();
 var mnths = new Array();
 var mnthsExpenses = new Array();
 for(i in a)
 {
  if(a[i]=="" || a[i]=="undefined") continue;
  tmp = a[i].split("|");
  profit = tmp[1] - tmp[2];
  for(p=4;p<tmp.length;p++)
  {
   if(mnths[p-4]==undefined) mnths[p-4] = 0;
   mnths[p-4] = Number(mnths[p-4]) + (Number(tmp[p])*profit);
   if(mnthsExpenses[p-4]==undefined) mnthsExpenses[p-4] = 0;
   mnthsExpenses[p-4] = Number(mnthsExpenses[p-4]) + (Number(tmp[p])*Number(tmp[2]));
  }
 }


    /*SYNCRONIZE THE MONTH SALES*/
    for(var i=0;i<=11;i++){
    	var preValue = $('input[preid=pre_month-' + i + ']').val();
	preValue = mnths[i];
    	$('input[preid=post_month-' + i + ']').val( preValue );   
    }

    /* SUBMIT THE DATA */
    $('#financial_plan_data_submit').click();
}


/** THIS FUNCTION IS USED TO SHOW THE FINANCIAL_PLAN_SECTION 
 */
function financial_plan_section_show(start_num,step_num,end_num,id_pre){
	for(var i= start_num; i<=end_num; i++){
		if( i != step_num){
	   		$("#"+ id_pre + i ).css({display:"none"});	
	   	}else{
	   		$("#" + id_pre + i).css({display:""});
	   	}
	   	
		if( i<=step_num){
			$("#financial_plan_progress_bar_" + i).css({"background":"#A41A56"});
		} else {
			$("#financial_plan_progress_bar_" + i).css({"background":"white"});
		}
		
	}
}

/**CHANGE THE MONTH INPUT NAME 
 */
function financial_plan_month_change(month){
	var month_data_url = get_financial_plan_data_url();
	financial_plan_refresh_modify_dialog_data(month_data_url, month);
	$("#financial_plan_data_month_sales").attr("name","month[" + month + "]");
	$("#financial_plan_data_modify_cost_off_month").val(month);
}

/**CHANGE THE MONTH INPUT OF THE FINANCIAL PLAN STEP FOUT*/
function financial_plan_step_4_choose_month(month){
	$('input[preid=post_chart-16]').val(month);
}

function financial_plan_step_4_choose_one_off_cost(value){
	$('input[preid=post_chart-24]').val(value);
}

/** CHANGE THE MONTH INPUT OF THE FINANCIAL PALN STEP ONE*/
function financial_plan_step_1_choose_month(month){
	$('input[preid=post_chart-17]').val(month);
}

/**CHANGE THE PRODUCT INPUT OF THE FINANCIAL PLAN STEP TWO*/
function financial_plan_step_2_choose_type(product_type){
	$('input[preid=post_chart-18]').val(product_type);
}

/**DISPLAY OR HIDE THE FIANACIAL_PLAN_DATA MODIFY DIV
 */
function financial_plan_data_modify_show(flag){
	if(flag == true){
		$("#financial_plan_data_modify_container" ).css({display:""});	
	} else {
		$("#financial_plan_data_modify_container" ).css({display:"none"});
	}
	
}

/**WHEN CLOSE THE DIALOG , REFRESH THE GOOGLE CHART
 */
function financial_plan_data_modify_refresh(){
	
	/* REFRESH THE GOOGLE CHART*/
	var data_from_url = get_financial_plan_data_url();
	var div_id = 'finacial_plan_div1';
	financial_plan_refresh_google_chart(data_from_url,div_id);

}



/**FETCH THE DATA FROM THE FINANCIAL FAKE FORM
 */
function financial_plan_fetch_fake_form_data(){
    var loss=0;
    
    /* FETCH & COUNT THE LOSS*/
    for(var i=0;i<=14;i++){
    	var tmpnum = $('input[preid=pre_chart-' + i + ']').val();
    	if( tmpnum != null && Number(tmpnum)!= NaN){
    		loss += Number(tmpnum);
    	}
    }
    var tmpdata = [
                   ['Jan',0,loss],
                   ['Feb',0,loss],
                   ['Mar',0,loss],
                   ['Apr',0,loss],
                   ['May',0,loss],
                   ['Jun',0,loss],
                   ['July',0,loss],
                   ['Aug',0,loss],
                   ['Sep',0,loss],
                   ['Oct',0,loss],
                   ['Nov',0,loss],
                   ['Dec',0,loss],
                   ];
    
    /* START MINUS THE COST OFF*/
    var cost_off_month = $('input[preid=post_chart-16]').val();
    if(cost_off_month > 0){
    	var cost_off = $('input[preid=pre_chart-15]').val()
    	tmpdata[ cost_off_month -1 ][2] = loss - cost_off;
    }
    
    //var cost_off = ;
    /* END MINUS THE COST OFF*/
    
    /* FETCH THE MONTH DATA  */
    for(var i=0;i<=11;i++){
    	tmpdata[i][1] = Number($('input[preid=pre_month-' + i + ']').val());   
    }
    return tmpdata;
}


/**CREATE GOOGLE CHART VIA JS
 */

function sids_chart(div_id)
{
    var start_balance = $('#pre_chart-19').val();
    var start_month = Number($('#sids_stmn').val()) - 1;
    if(start_month<0) start_month = 0;
//    alert(start_month);
    var expenses = 0;
    var loss = 0;
    var tmpdata = [
                   ['Jan',0,loss],
                   ['Feb',0,loss],
                   ['Mar',0,loss],
                   ['Apr',0,loss],
                   ['May',0,loss],
                   ['Jun',0,loss],
                   ['July',0,loss],
                   ['Aug',0,loss],
                   ['Sep',0,loss],
                   ['Oct',0,loss],
                   ['Nov',0,loss],
                   ['Dec',0,loss],
                   ];




 var x = getCookie("s_res2"+"_"+$("#my_id").val()); // get one off expenses
//alert(x);
 var a = x.split("\r\n");
//alert(a);
 for(i in a)
 {
  if(a[i]=="" || a[i]=="undefined") continue;
 // alert(a[i]);
  tmp = a[i].split("|");
//alert(tmp);
//alert(tmp);
  var amnt = tmp[1];
  var mnth = Number(tmp[2])-1;
//alert(mnth);
  tmpdata[mnth][2] = Number(tmpdata[mnth][2]) + amnt;
 }

 tmpdata[start_month][2] = Number(tmpdata[start_month][2]) + start_balance;


 var x = getCookie("s_res"+"_"+$("#my_id").val());
 var a = x.split("\r\n");
 var na = new Array();
 var mnths = new Array();
 var mnthsExpenses = new Array();
 for(i in a)
 {
  if(a[i]=="" || a[i]=="undefined") continue;
//  alert(a[i]);
  tmp = a[i].split("|");
//  delete tmp[0];
//  delete tmp[1];
//  expenses += tmp[2];
//  delete tmp[2];
//  delete tmp[3];
//  alert(tmp);
  profit = tmp[1] - tmp[2];
  for(p=4;p<tmp.length;p++)
  {
   if(mnths[p-4]==undefined) mnths[p-4] = 0;
   mnths[p-4] = Number(mnths[p-4]) + (Number(tmp[p])*profit);
   if(mnthsExpenses[p-4]==undefined) mnthsExpenses[p-4] = 0;
   mnthsExpenses[p-4] = Number(mnthsExpenses[p-4]) + (Number(tmp[p])*Number(tmp[2]));
  }
 }
// alert(mnths);

 var miscellaneousExpenses =0; 
 for(j=0;j<15;j++)
 {
  var v = $('input[preid=post_chart-'+j+']').val();
  if(v!="")
  {
   miscellaneousExpenses += v;
  }
 }
// alert(miscellaneousExpenses);

    /* START MINUS THE COST OFF*/
/*
    var cost_off_month = $('input[preid=post_chart-16]').val();
    if(cost_off_month > 0){
    	var cost_off = $('input[preid=pre_chart-15]').val()
    	tmpdata[ cost_off_month -1 ][2] = loss + cost_off;
    }
*/  
    //var cost_off = ;
    /* END MINUS THE COST OFF*/
    
    /* FETCH THE MONTH DATA  */
    for(var i=0;i<=11;i++){
//	alert(mnths[i]);
    	tmpdata[i][1] = mnths[i];
    	tmpdata[i][2] = Number(tmpdata[i][2]) + mnthsExpenses[i]+miscellaneousExpenses;
    }


    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Year');
    data.addColumn('number', 'Sales');
    data.addColumn('number', 'Expenses');
   
    data.addRows(tmpdata.length);
    for(var i=0;i<tmpdata.length;i++){
    	data.setValue(i,0,tmpdata[i][0]);
    	data.setValue(i,1,tmpdata[i][1]);
    	data.setValue(i,2,tmpdata[i][2]);
    }
    
    var options = {
    		width: 931, height: 240, title: 'Company Performance',
            hAxis: {title: 'Year', titleTextStyle: {color: 'red'},
            	},
            colors:['#417CD6','#A41A56']
    };
    var chart = new google.visualization.ColumnChart(document.getElementById(div_id));
    chart.draw(data, options);
}

function financial_plan_create_chart(tmpdata,div_id){
	var data = new google.visualization.DataTable();
    data.addColumn('string', 'Year');
    data.addColumn('number', 'Sales');
    data.addColumn('number', 'Expenses');
    data.addColumn('number', 'Profit');
   
    data.addRows(tmpdata.length);
    for(var i=0;i<tmpdata.length;i++){
    	data.setValue(i,0,tmpdata[i][0]);
    	data.setValue(i,1,tmpdata[i][1]);
    	data.setValue(i,2,tmpdata[i][2]);
    }
    
    var options = {
    		width: 931, height: 240, title: 'Company Performance',
            hAxis: {title: 'Year', titleTextStyle: {color: 'red'},
            	},
            colors:['#417CD6','#A41A56']
    };
    var chart = new google.visualization.ColumnChart(document.getElementById(div_id));
    chart.draw(data, options);
}


/**THIS FUNCTION FETCH THE DATA AND THEN DARW THE GOOGLE CHART TO THE DIV 
 * THE DATA IS FETCH FROM THE SERVER TABLE
 */
function google_bar_chart_draw(chart_data,div_id){
	var items = eval(chart_data);
	if (items.length) {
		var data = new google.visualization.DataTable();
	    data.addColumn('string', 'Month');
	    data.addColumn('number', 'Sales');
	    data.addColumn('number', 'Expenses');
	    data.addRows(12);
	    
	    for(var i=0; i<items.length; i++){
	    	var item = null;
	    	item = eval(items[i]);
	    	data.setValue(i, 0, item['month']);
	    	data.setValue(i, 1, parseInt(item['sales']));
	    	data.setValue(i, 2, parseInt(item['expenses']));
	    }
	    
	    var options = {width: 931, height: 240, title: 'Company Performance',
	            hAxis: {title: 'Year', titleTextStyle: {color: 'red'},
	            },
	            colors:['#417CD6','#A41A56']
	    };
	    
	    var chart1 = new google.visualization.ColumnChart(document.getElementById(div_id));
	    chart1.draw(data, options);
	}
	
}

/**DISPLAY THE GOOGLE COLUMN CHART 
 */
function financial_plan_refresh_google_chart(data_from_url,div_id){
	$.ajax({
	    type: "POST",
	    url: data_from_url ,
	    data: "",
	    success: function(chart_data){
	    	/* DRAW THE GOOGLE CHART*/
	    	google_bar_chart_draw(chart_data,div_id);
	    }
	});
}

/**	THIS FUNCTION IS USED TO REFRESH DATA OF THE FINANCIAL PLAN DATA MODIFY FANCY BOX
 */
function financial_plan_refresh_modify_dialog_data(month_data_from_url, month){
	$.ajax({
		type: "POST",
		url: month_data_from_url,
		data: "month=" + month ,
		dataType: 'json',
		success: function(month_data){
			$("#financial_plan_data_month_sales").val(month_data[0].sales);
			
			var id_pre = 'financial_plan_data_modify_';
			
			$("#" + id_pre + "salary").val(month_data[0].salary);
			$("#" + id_pre + "payroll").val(month_data[0].payroll);
			$("#" + id_pre + "supplies").val(month_data[0].supplies);
			$("#" + id_pre + "advertising").val(month_data[0].advertising);
			$("#" + id_pre + "car_travel").val(month_data[0].car_travel);
			$("#" + id_pre + "delivery").val(month_data[0].delivery);
			$("#" + id_pre + "utilities").val(month_data[0].utilities);
			$("#" + id_pre + "insurance").val(month_data[0].insurance);
			$("#" + id_pre + "accounts").val(month_data[0].accounts);
			$("#" + id_pre + "legal").val(month_data[0].legal);
			$("#" + id_pre + "rent").val(month_data[0].rent);
			$("#" + id_pre + "telephones").val(month_data[0].telephones);
			$("#" + id_pre + "taxes").val(month_data[0].taxes);
			$("#" + id_pre + "other").val(month_data[0].other);
			$("#" + id_pre + "cost_off").val(month_data[0].cost_off);
		}
	});
}

/**WHEN ONLOAD THE DOCUMENT ,THIS FUNCTION DECIDES TO SHOW WHICH FINANCIAL_PLAN SECTION
 *IF USER NOT SUBMIT THE CHART DATA ,THEN SHOW THE FIVE STEP ELSE SHOW THE GOOGLE CHART
 */
function financial_plan_show(data_from_url,div_id){
	$.ajax({
	    type: "POST",
	    url: data_from_url,
	    data: "",
	    success: function(chart_data){
	    	if( chart_data == 'null'){
	    		$("#financial_plan_chart_data_not_submit_yet").css({display:"block"});
	    		$("#financial_plan_chart_data_already_submit").css({display:"none"});
	    	}else{
	    		$("#financial_plan_chart_data_not_submit_yet").css({display:"none"});
	    		$("#financial_plan_chart_data_already_submit").css({display:"block"});
	    		
	    		/* DRAW THE GOOGLE CHART*/
	    		google_bar_chart_draw(chart_data,div_id);
	    		
	    		/*INITIAL THE FINANCIAL DATA MODIFY DIALOG*/
	    		var month_data_from_url = get_financial_plan_data_url();
	    		var month = 1 ;
	    		financial_plan_refresh_modify_dialog_data(month_data_from_url, month);
	    	}
	    }
	});
    	
}



/**ADD THE CLICK FUNCTION TO THE FINANCIAL_PLAN CONTINUE BUTTON AND BACK BUTTON AND THE RESET BUTTON 
 */
$(document).ready(function(){
	
	
	 /* DISPLAY THE STEP ONE DIV WHEN STARTED*/	
	financial_plan_section_show(1, 1, 5 , 'financial_plan_step_');
	
	/* ADD THE EVENT TO THE STEP BUTTON */
	$(".financial_plan_step_button").click(function(){
		var buttonid = this.id; 
        var buttonid_arr = buttonid.split('_');
        var step_num = buttonid_arr[ buttonid_arr.length - 1 ];
        var id_pre = 'financial_plan_step_';
        financial_plan_section_show(1, step_num, 5 , id_pre );
        
	});
	
	
    
	/* FIX THE BUG WHEN CLICK THE RESET BUTTON THE ONCHANGE EVEN OF SELECT  DOESN'T TRIGGER*/
	$("#financial_plan_data_reset").click(function(){
		$("#financial_plan_data_month").attr("name","month[1]");	
	});
	
	/* WHEN WALK TO STEP 5,THEN CREATE THE CHART VIA JS */
	$("#financial_plan_go_5").click(function(){ 
		
//		var tmpdata = financial_plan_fetch_fake_form_data();
		var div_id = 'financial_plan_chart_via_js';
		
//		financial_plan_create_chart(tmpdata,div_id);
		sids_chart(div_id);
	});

});

google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(function(){	
	var data_from_url = get_financial_plan_data_url();
	var div_id = 'finacial_plan_div1';
	financial_plan_show(data_from_url,div_id);
});




function add_ooc()
{
 what_for = $('input[preid=pre_chart-23]').val();
 $('input[preid=pre_chart-23]').val('');
 if(what_for=="") return;
 how_much = $('input[preid=pre_chart-15]').val();
 $('input[preid=pre_chart-15]').val('');
 whenn = $('#ooc_mnth').val();
//alert(whenn);
 $('input[preid=pre_chart-16]').val('');
 r = what_for + "|" + how_much + "|" + whenn;
 setCookie("s_res2"+"_"+$("#my_id").val(),getCookie("s_res2"+"_"+$("#my_id").val())+"\r\n" + r);
 show_oocs();
}

function show_oocs()
{
 if($('#sids_oocs'))
 {
  $('#sids_oocs').html('');
  var x = getCookie("s_res2"+"_"+$("#my_id").val());
  if(x=="" || x==undefined) return;
  var a = x.split("\r\n");
  for(i in a)
  {
   d = a[i];
   if(d=="" || d==undefined) continue;
   tmp = d.split("|",1);
   if(tmp == "undefined") continue;
   html = "<div style='width:400px;clear:right;padding:4px;font-family:arial;margin:2px;height:20px;'>" + tmp + "<span style='height:16px;float:right;color:pink;cursor:pointer;font-weight:bold' onclick=\"delete_ooc("+i+")\">Delete</span></div>";
   $("#sids_oocs").html($("#sids_oocs").html()+html);
  }  
 }

}

function add_product()
{
 var pn = $('input[preid=pre_chart-20]').val();
 if(pn=="") return;
 var ch = $('input[preid=pre_chart-21]').val();
 var cst = $('input[preid=pre_chart-22]').val();
 var pos = $('#s_pos').val();
 var jan = $('input[preid=pre_month-0]').val();
 var feb = $('input[preid=pre_month-1]').val();
 var mar = $('input[preid=pre_month-2]').val();
 var apr = $('input[preid=pre_month-3]').val();
 var may = $('input[preid=pre_month-4]').val();
 var jun = $('input[preid=pre_month-5]').val();
 var jul = $('input[preid=pre_month-6]').val();
 var aug = $('input[preid=pre_month-7]').val();
 var sep = $('input[preid=pre_month-8]').val();
 var oct = $('input[preid=pre_month-9]').val();
 var nov = $('input[preid=pre_month-10]').val();
 var dec = $('input[preid=pre_month-11]').val();
 
 $('input[preid=pre_chart-20]').val('');
 $('input[preid=pre_chart-21]').val('');
 $('input[preid=pre_chart-22]').val('');
 $('#s_pos').val('');
 $('input[preid=pre_month-0]').val('');
 $('input[preid=pre_month-1]').val('');
 $('input[preid=pre_month-2]').val('');
 $('input[preid=pre_month-3]').val('');
 $('input[preid=pre_month-4]').val('');
 $('input[preid=pre_month-5]').val('');
 $('input[preid=pre_month-6]').val('');
 $('input[preid=pre_month-7]').val('');
 $('input[preid=pre_month-8]').val('');
 $('input[preid=pre_month-9]').val('');
 $('input[preid=pre_month-10]').val('');
 $('input[preid=pre_month-11]').val('');

 var r = pn + "|" + ch + "|" + cst + "|" + pos + "|" + jan + "|" + feb + "|" + mar + "|" + apr + "|" + may + "|" + jun + "|" + jul + "|" + aug + "|" + sep + "|" + oct + "|" + nov + "|" + dec;
 setCookie("s_res"+"_"+$("#my_id").val(),getCookie("s_res"+"_"+$("#my_id").val())+"\r\n" + r);
// var time = Date.parse(new Date());
// alert(time);
 var x = getCookie("s_res"+"_"+$("#my_id").val());
 var a = x.split("\r\n");
 for(i in a)
 {
  d = a[i];
  tmp = d.split("|",1);
  html = "<div>" + tmp + "</div>";
  $("#sids_products").html($("#sids_products").html()+html);
 }
 show_products();
// alert(a);
// alert(x);
 //alert($('input[preid=pre_chart-20]').val());
}


function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function delete_product(id)
{
 var x = getCookie("s_res"+"_"+$("#my_id").val());
 var a = x.split("\r\n");
 var na = new Array();
 for(i in a)
 {
  if(i!=id) na.push(a[i]);
 }
 tmp = na.join("\r\n");
 setCookie("s_res"+"_"+$("#my_id").val(),tmp);
 if(id==0) {setCookie("s_res"+"_"+$("#my_id").val(),"");}
 show_products();
}


function delete_ooc(id)
{
 var x = getCookie("s_res2"+"_"+$("#my_id").val());
 var a = x.split("\r\n");
 var na = new Array();
 for(i in a)
 {
  if(i!=id) na.push(a[i]);
 }
 tmp = na.join("\r\n");
 setCookie("s_res2"+"_"+$("#my_id").val(),tmp);
 if(id==0) {setCookie("s_res2"+"_"+$("#my_id").val(),"");}
 show_oocs();
}


function show_products()
{
 if($('#sids_products'))
 {
  $('#sids_products').html('');
  var x = getCookie("s_res"+"_"+$("#my_id").val());
  if(x=="" || x==undefined) return;
  var a = x.split("\r\n");
  for(i in a)
  {
   d = a[i];
   if(d=="" || d==undefined) continue;
   tmp = d.split("|",1);
   if(tmp == "undefined") continue;
   html = "<div style='width:400px;clear:right;padding:4px;font-family:arial;margin:2px;'>" + tmp + "<span style='height:16px;float:right;color:pink;cursor:pointer;font-weight:bold' onclick=\"delete_product("+i+")\">Delete</span></div>";
   $("#sids_products").html($("#sids_products").html()+html);
  }  
 }
}

$(document).ready(function()
{
 show_products();
 show_oocs();
});
